package Java8.stramparalle;

import java.util.Optional;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;
import org.apache.directory.api.util.Strings;
import org.apache.kerby.util.HexUtil;

public class ForkJoinTest extends RecursiveTask<Long> {

    private final long[] numbers;
    private final int start;
    private final int end;

    public static final long THRESHOLD = 1000;

    public ForkJoinTest(long[] numbers) {
        this(numbers, 0, numbers.length);
    }

    private ForkJoinTest(long[] numbers, int start, int end) {
        this.numbers = numbers;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        int length = end - start;
        if (length <= THRESHOLD) {
            return computeSequentially();
        }

        ForkJoinTest leftTask = new ForkJoinTest(numbers, start, start + length / 2);
        leftTask.fork();

        ForkJoinTest rigthTask = new ForkJoinTest(numbers, start + length / 2, end);

        Long rightResult = rigthTask.compute();
        Long leftResult = leftTask.join();

        return leftResult + rightResult;
    }

    private long computeSequentially() {
        long sum = 0;
        for (int i = start; i < end; i++) {
            sum += numbers[i];
        }
        return sum;
    }

    public static long forkJoinSum(long n) {

        long[] numbers = LongStream.rangeClosed(1, n).toArray();

        ForkJoinTask<Long> task = new ForkJoinTest(numbers);
        return new ForkJoinPool().invoke(task);
    }

    public static void main(String[] args) {

        System.out.println(new String(HexUtil.hex2bytes("4d")));
        System.out.println(new String(HexUtil.hex2bytes("61")));
        System.out.println(new String(HexUtil.hex2bytes("72")));

        int i = 1337;
        System.out.println(Integer.toHexString(i));

        System.out.println(Strings.toHexString("M".getBytes()));

        System.out.println(new String(HexUtil.hex2bytes("0b")));

        System.out.println("=========");
        System.out.println(new String(HexUtil.hex2bytes("05")));
        System.out.println("=========");

        System.out.println(new String(HexUtil.bytesToHex("1337".getBytes())));
        System.out.println(forkJoinSum(1001));

        Optional<String> optionalS = Optional.ofNullable("444");

        System.out.println(optionalS.get());
        System.out.println(optionalS.get());
        System.out.println(optionalS.get());
    }
}
